<template>
	<div class="base">
		<div class="title">
			{{ $route.meta.title }}
			<i @click="showCourse = !showCourse" class="iconfont icon-question-circle"></i>
		</div>
		<div class="course" v-show="showCourse">
			<p><span class="black">1、同步企业微信创建的客户群，实时查看群状态。</span></p>
			<p><span class="black">2、群二维码可用于自动入群、标签拉群入群二维码推送，群二维码应根据有效期及时更新。</span></p>
			<p><span class="black">3、可为群聊成员设置群激励目标，关注成员群引流效果。</span></p>
		</div>
		<div class="inputs-flex">
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="群名称"><el-input size="small" maxlength="20" v-model="formInline.name" placeholder="请输入"></el-input></el-form-item>
				<el-form-item label="群主"><el-input size="small" maxlength="20" v-model="formInline.owner_user_name" placeholder="请输入"></el-input></el-form-item>
				<el-form-item label="客户群标签">
					<el-cascader
						@visible-change="
							visible => {
								if (visible && tagsList.length === 0) {
									getTagsList();
								}
							}
						"
						size="small"
						v-model="tag_ids"
						:options="tagsList"
						:show-all-levels="false"
						:props="{ expandTrigger: 'hover', children: 'group', label: 'name', value: 'id', multiple: true }"
					></el-cascader>
				</el-form-item>
				<el-form-item><el-button size="small" class="btn-blue" @click="onSearch">查询</el-button></el-form-item>
			</el-form>
			<div class="btns">
				<download-excel class="right export" :data="json_data" :fields="json_fields" type="csv" worksheet="My Worksheet" :name="`${$route.meta.title}列表.xls`">
					<el-button
						size="small"
						:icon="out ? 'el-icon-loading' : ''"
						:disabled="selectList.length == 0 || out"
						:class="selectList.length != 0 ? 'btn-white' : 'btn-opacity'"
						@click.stop="handleExport"
					>
						{{ out ? '正在导出...' : '导出群聊' }}
					</el-button>
				</download-excel>
				<el-button size="small" :class="selectList.length === 0 ? 'btn-opacity' : 'btn-white'" :disabled="selectList.length === 0" @click="onAddTag">打标签</el-button>
				<el-button size="small" :class="selectList.length === 0 ? 'btn-opacity' : 'btn-white'" :disabled="selectList.length === 0" @click="onDelTag">移除标签</el-button>
			</div>
		</div>

		<div class="table">
			<el-table
				v-loading="loading1"
				ref="Table"
				id="export-table"
				:data="tableData"
				tooltip-effect="dark"
				style="width: 100%"
				:header-cell-style="{
					color: '#333',
					fontSize: '14px',
					backgroundColor: '#F6F7FB',
					fontWeight: 'normal'
				}"
				@cell-click="handleCellClick"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="name" label="群名称">
					<template slot-scope="scope">
						<span class="active">{{ scope.row.name || '--' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="跟进状态" width="120" align="center"></el-table-column>
				<el-table-column prop="number" label="群人数/目标人数" width="200" align="center">
					<template slot="header">
						客户数/目标客户数
						<el-tooltip class="item" content="显示下一激励目标人数，已达标目标客前往群详情-激励详情中查看" placement="top">
							<i class="iconfont icon-question-circle"></i>
						</el-tooltip>
					</template>
					<template slot-scope="scope">
						{{ scope.row.number || 0 }}/{{ scope.row.target || 0 }}
					</template>
				</el-table-column>
				<el-table-column prop="owner_name" label="群主" width="120" align="center"></el-table-column>
				<el-table-column label="群标签" align="center">
					<template v-slot="scope">
						<template v-if="scope.row.tag_ids">
							<div style="display: flex;align-items: center;flex-wrap: wrap;justify-content: center;">
								<div style="padding: 5px;" v-for="(tag, index) in scope.row.tag_ids" :key="index">
									<el-tag>{{ tag }}</el-tag>
								</div>
							</div>
						</template>
						<span v-else>--</span>
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
				<el-table-column prop="qr_code" width="150" align="center">
					<template slot="header">
						群二维码
						<i
							style="cursor: pointer;"
							class="iconfont icon-question-circle"
							@click="
								() => {
									$bus.$emit('showHelp', 16);
								}
							"
						></i>
					</template>
					<template slot-scope="scope">
						<el-image
							fit="cover"
							:z-index="9999"
							v-if="scope.row.qr_code"
							style="width: 100px; height: 100px"
							:src="scope.row.qr_code"
							@click.stop="$closeImg"
							:preview-src-list="scope.row.qr_code ? [scope.row.qr_code] : []"
						></el-image>
						<span v-else>--</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200" align="center">
					<template slot-scope="scope">
						<div class="flex-btns">
							<el-button v-if="scope.row.qr_code" type="text" @click="handleEditQrCode(scope.row)">更换群二维码</el-button>
							<el-button v-else type="text" @click="handleEditQrCode(scope.row)">上传群二维码</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pagination" v-if="total !== 0">
			<el-pagination
				@size-change="handleLimitChange"
				@current-change="handlePageChange"
				:current-page="page"
				:page-sizes="[10, 20, 50, 100]"
				:page-size="limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>
		<!-- 上传群二维码模态框 -->
		<el-dialog title="上传群二维码" :visible.sync="uploadVisible" width="450px" :before-close="uploadClose" :close-on-click-modal="false">
			<el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm" label-position="left" label-width="100px" class="uploadForm">
				<el-form-item label="群名称" required>
					<span>{{ uploadForm.name || '--' }}</span>
				</el-form-item>
				<el-form-item label="群二维码" prop="url">
					<div class="flex">
						<el-upload
							v-if="uploadVisible"
							:class="hideUpload ? 'hide upload' : 'upload'"
							:action="action"
							:data="$uploadParams()"
							name="image"
							list-type="picture-card"
							:before-upload="beforeImgUpload"
							:on-remove="uploadImgRemove"
							:on-change="uploadImgChange"
							:on-success="uploadSuccess"
						>
							<i class="el-icon-plus"></i>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过2M</div>
						</el-upload>
						<i
							class="iconfont icon-question-circle"
							@click="
								() => {
									$bus.$emit('showHelp', 16);
								}
							"
						></i>
					</div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" class="btn-white" @click="uploadClose">取 消</el-button>
				<el-button size="small" class="btn-blue" @click="handleUploadSubmit">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 客户群详情抽屉 -->
		<el-drawer title="标题" :visible.sync="drawer" size="1000px" :with-header="false">
			<div v-loading="loading2">
				<div class="drawer-header">
					<el-image fit="cover" style="width: 100px; height: 100px" :src="drInfo.qr_code" :z-index="9999" @click.stop="$closeImg" :preview-src-list="[drInfo.qr_code]">
						<div slot="error" class="image-slot"><i class="el-icon-picture-outline"></i></div>
					</el-image>
					<div style="margin-left: 15px">
						<p>{{ drInfo.name }}</p>
						<p>
							<span class="circle"></span>
							<span>{{ drInfo.status }}</span>
						</p>
						<p>
							<span>{{ drInfo.owner_name }}</span>
							<span>创建时间：{{ drInfo.create_time }}</span>
						</p>
						<div style="display: flex;align-items: center;flex-wrap: wrap;margin-left: -5px;">
							<div v-for="(tag, index) in drInfo.tag_name" style="padding: 5px;" :key="index">
								<el-tag :key="index">{{ tag }}</el-tag>
							</div>
						</div>
					</div>
					<i class="el-icon-close" @click="drawer = false"></i>
				</div>
				<el-tabs v-model="tabNum">
					<el-tab-pane label="群成员列表" name="0">
						<div class="inputs">
							<el-form :inline="true" :model="formInline" class="demo-form-inline">
								<el-form-item label="成员"><el-input size="small" maxlength="20" v-model="formInline.drName" placeholder="请输入"></el-input></el-form-item>
								<el-form-item><el-button size="small" class="btn-blue" @click="onDrSearch">查询</el-button></el-form-item>
							</el-form>
						</div>
						<div class="table">
							<el-table
								height="calc(100vh - 370px)"
								:data="drTableData"
								tooltip-effect="dark"
								style="width: 100%"
								:header-cell-style="{
									color: '#333',
									fontSize: '14px',
									backgroundColor: '#F6F7FB',
									fontWeight: 'normal'
								}"
							>
								<el-table-column prop="name" label="群成员">
									<template slot-scope="scope">
										{{ scope.row.name || '--' }}
									</template>
								</el-table-column>
								<el-table-column prop="user_type" label="成员类型"></el-table-column>
								<el-table-column prop="join_scene" label="进群方式"></el-table-column>
								<el-table-column prop="invitor" label="邀请者">
									<template v-slot="scope">
										<span>{{ scope.row.invitor || '--' }}</span>
									</template>
								</el-table-column>
								<el-table-column prop="join_time" label="进群时间" width="180"></el-table-column>
							</el-table>
						</div>
						<div class="pagination" v-if="drTotal !== 0">
							<el-pagination
								@size-change="
									limit => {
										drPageSize = limit;
										getDetaliList();
									}
								"
								@current-change="
									page => {
										drCurrentPage = page;
										getDetaliList();
									}
								"
								:current-page="drCurrentPage"
								:page-sizes="[10, 20, 50, 100]"
								:page-size="drPageSize"
								layout="total, sizes, prev, pager, next, jumper"
								:total="drTotal"
							></el-pagination>
						</div>
					</el-tab-pane>
				</el-tabs>
			</div>
		</el-drawer>
		<!-- 打标签/移除标签 -->
		<edit-label-dialog ref="edit-label-dialog" :isGroup="true" @update:list="getDataList()"></edit-label-dialog>
	</div>
</template>

<script>
import {
	reqGetCustomGroupList,
	reqGetCustomGroupInfo,
	uploadQrcodeUrl,
	reqEditGroupQrcode,
	reqShowGroupTarget,
	reqGroupTargetGrant,
	reqGetSoloStaff,
	reqGetCustomTree
} from '@/api/index';
import EditLabelDialog from '@/hkm/EditCustomerLabel';
export default {
	components: {
		EditLabelDialog
	},
	data() {
		return {
			formInline: {
				name: '',
				owner_user_name: '',
				drName: '',
				drId: ''
			},
			showCourse: false,
			loading1: false,
			loading2: false,
			page: 1,
			limit: 10,
			total: 0,
			tableData: [],
			uploadVisible: false,
			selectList: [],
			out: false,
			json_fields: {
				群名称: 'name',
				跟进状态: 'status',
				群人数: 'number',
				目标人数: 'target',
				群主: 'owner_name',
				创建时间: 'create_time',
				群二维码: 'qr_code'
			},
			json_data: [],
			uploadForm: {
				name: '',
				url: '',
				media_id: '',
				id: ''
			},
			uploadRules: {
				url: [
					{
						required: true,
						message: '请上传群二维码',
						trigger: 'change'
					}
				]
			},
			bigImageUrl: '',
			bigImgVisible: false,
			disabled: false,
			drawer: false,
			drCurrentPage: 1,
			drPageSize: 10,
			drTotal: 0,
			drInfo: {},
			drTableData: [],
			hideUpload: false,
			action: '',
			fileList: [],
			/**群详情标签页 */
			tabNum: '0',
			drTableData1: [],
			num: null,
			tagsList: [],
			tag_ids: [],
			timer: null
		};
	},
	watch: {
		'formInline.owner_user_name': {
			handler(val) {
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.page = 1;
					this.getDataList();
				}, 300);
			}
		},
		'formInline.name': {
			handler(val) {
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.page = 1;
					this.getDataList();
				}, 300);
			}
		},
		'formInline.drName': {
			handler(val) {
				!val ? this.getDetaliList() : '';
			}
		},
		tag_ids() {
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				this.page = 1;
				this.getDataList();
			}, 300);
		},
		'uploadForm.url': {
			handler(val) {
				val ? this.$refs.uploadForm.validateField('url') : '';
				val ? (this.hideUpload = true) : (this.hideUpload = false);
			},
			deep: true
		},
		drawer(val) {
			!val ? ((this.formInline.drName = ''), (this.tabNum = '0')) : '';
		},
		tabNum(val) {
			val == '1' ? this.getJlDetail() : '';
		}
	},
	created() {
		this.action = uploadQrcodeUrl;
		Promise.all([
			reqGetSoloStaff({
				page: 1,
				limit: 10000
			}),
			this.getDataList()
		]).then(res => {
			this.soloStaffList = res[0].data;
		});
	},
	methods: {
		// 获取客户标签树结构
		getTagsList() {
			reqGetCustomTree({}).then(res => {
				this.tagsList = res.data;
			});
		},
		// 获取数据列表
		getDataList() {
			this.loading1 = true;
			reqGetCustomGroupList({
				page: this.page,
				limit: this.limit,
				name: this.formInline.name,
				tag_ids: this.tag_ids.join(','),
				owner_user_name: this.formInline.owner_user_name
			}).then(res => {
				this.loading1 = false;
				this.tableData = res.data;
				this.total = res.count || 0;
			});
		},
		// 查询
		onSearch() {
			this.page = 1;
			this.getDataList();
		},
		handleLimitChange(limit) {
			this.limit = limit;
			this.getDataList();
		},
		handlePageChange(page) {
			this.page = page;
			this.getDataList();
		},
		// 上传群二维码模态框关闭
		uploadClose() {
			this.$refs.uploadForm.clearValidate();
			this.uploadVisible = false;
		},
		// 多选发生变化
		handleSelectionChange(list) {
			this.selectList = list;
		},
		// 删除上传图片
		uploadImgRemove(file, fileList) {
			this.hideUpload = fileList.length >= 1;
		},
		uploadImgChange(file, fileList) {
			this.hideUpload = fileList.length >= 1;
		},
		beforeImgUpload(file) {
			const isJPG = file.type === 'image/jpg';
			const isJPEG = file.type === 'image/jpeg';
			const isPNG = file.type === 'image/png';
			const isLt2M = file.size / 1024 / 1024 <= 2;
			if (!isJPG && !isJPEG && !isPNG) {
				this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!');
			} else if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!');
			}
			return (isJPG && isLt2M) || (isLt2M && isJPEG) || (isLt2M && isPNG);
		},
		// 获取群详细数据
		getDetaliList() {
			this.loading2 = true;
			reqGetCustomGroupInfo({
				page: this.drCurrentPage,
				limit: this.drPageSize,
				id: this.formInline.drId,
				name: this.formInline.drName
			}).then(res => {
				this.loading2 = false;
				this.drInfo = res.data.info;
				this.drTableData = res.data.list;
				this.drTotal = res.count;
			});
		},
		// 获取激励详情
		getJlDetail() {
			this.loading2 = true;
			reqShowGroupTarget({
				id: this.formInline.drId
			}).then(res => {
				this.loading2 = false;
				this.drTableData1 = res.data;
			});
		},
		// 表格单元格被点击
		handleCellClick(row, column) {
			column.label === '群名称' ? ((this.drawer = true), (this.formInline.drId = row.id), this.getDetaliList()) : '';
		},
		onDrSearch() {
			this.formInline.drName ? this.getDetaliList() : '';
		},
		handleEditQrCode(row) {
			this.uploadForm = {
				name: row.name,
				url: '',
				media_id: '',
				id: row.id
			};
			this.uploadVisible = true;
		},
		uploadSuccess(res) {
			if (res.code === 200) {
				this.uploadForm.url = res.data.url;
				this.uploadForm.media_id = res.data.media_id;
			} else {
				this.$message.success(res.msg);
			}
		},
		handleUploadSubmit() {
			this.$refs.uploadForm.validate(valid => {
				if (valid) {
					delete this.uploadForm.name;
					reqEditGroupQrcode(this.uploadForm).then(res => {
						this.$message.success(res.msg);
						this.uploadVisible = false;
						this.getDataList();
					});
				} else {
					return false;
				}
			});
		},
		// 导出群聊
		handleExport(e) {
			this.out = true;
			this.json_data = this.selectList;
			setTimeout(() => {
				this.out = false;
				document.querySelector('.export').click();
			}, 1000);
		},
		// 打标签
		onAddTag() {
			this.$refs['edit-label-dialog'].form = { id: this.selectList.map(v => v.id), type: 1, table_name: 'wxk_customer_group' };
			this.$refs['edit-label-dialog'].type = 'add';
			this.$refs['edit-label-dialog'].dialogVisible = true;
		},
		// 移除标签
		onDelTag() {
			this.$refs['edit-label-dialog'].form = { id: this.selectList.map(v => v.id), type: 2, table_name: 'wxk_customer_group' };
			this.$refs['edit-label-dialog'].type = 'del';
			this.$refs['edit-label-dialog'].dialogVisible = true;
		}
	}
};
</script>

<style lang="less" scoped>
.base {
	width: 100%;
	overflow: hidden;

	.inputs {
		margin: 15px 0;
	}
	.inputs-flex {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.btns {
		display: flex;
		align-items: center;
		> div {
			margin-right: 10px;
		}
	}

	.table {
		margin-top: 15px;

		span.active {
			cursor: pointer;
			color: #6881ec;
		}

		.img-wrap {
			position: relative;
			width: 100px;
			height: 100px;

			.mask {
				visibility: hidden;
				position: absolute;
				top: 0;
				left: 0;
				width: 100px;
				height: 100px;
				background-color: rgba(0, 0, 0, 0.5);
				border-radius: 0px;
				color: #fff;
				cursor: pointer;
			}

			&:hover .mask {
				visibility: visible;
			}
		}

		.flex-btns {
			display: flex;
			flex-wrap: wrap;

			> .el-button {
				margin: 0 5px;
			}
		}
	}

	.flex {
		display: flex;
		margin-top: 15px;

		> i {
			height: 20px;
			line-height: 20px;
			vertical-align: middle;
		}
	}

	.drawer-header {
		padding: 20px 0;
		display: flex;
		// align-items: center;

		> img {
			width: 80px;
			margin-right: 15px;
		}

		> div {
			height: 105px;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			> p:nth-child(1) {
				color: #6881ec;
				font-size: 16px;
			}

			> p:nth-child(2) {
				display: flex;
				align-items: center;
				color: #67c23a;
				font-size: 14px;

				.circle {
					width: 10px;
					height: 10px;
					border-radius: 50%;
					background-color: rgb(5, 143, 5);
					margin-right: 10px;
				}
			}

			> p:nth-child(3) {
				display: flex;
				align-items: center;
				color: #333;
				font-size: 12px;

				span + span {
					margin-left: 10px;
				}
			}
		}

		i {
			margin-left: auto;
			color: #ffbbc0;
			font-size: 20px;
			font-weight: bold;
			cursor: pointer;
			align-self: flex-start;
		}
	}

	.hr {
		/deep/.el-form-item__content {
			margin-left: 0px !important;
		}
	}

	.hr-class {
		width: 100%;
		height: 1px;
		background-color: #efefef;
		margin: 10px 0 20px;
	}

	.setForm {
		.el-input {
			width: 300px;
		}
	}

	.setForm {
		.hr {
			width: 100%;
		}
	}
}
</style>
<style>
.hide .el-upload--picture-card {
	display: none;
}
</style>
